<?php

/**
 * 用来记录日志的文件writer
 *
 * @version $Id: IFileLogWriter.php 330 2008-05-30 15:33:05Z iwind $
 * @package util.log.writer
 */
class IFileLogWriter extends IObject implements ILogWriter {
	/**
	 * Enter description here...
	 *
	 * @var IFileAppender
	 */
	private $appender;
	private $ready = true;
	
	/**
	 * 构造
	 *
	 * $filename可以为 log/%Y%m%d%H%i%s.log.
	 * 
	 * @param string $filename 文件名
	 */
	public function __construct($filename) {
		$filename = $this->logFormat($filename);
		$file = new IFile($filename);
		if ((!$file->exists() && !$file->parentFile()->canWrite()) || ($file->exists() && !$file->canWrite())) {
			ILog::singleton()->warning("can't append log to '{$filename}', please check write permission");
			$this->ready = false;
		}
		$this->appender = $file->appender();
	}
	
	/**
	 * 写入信息
	 *
	 * @param string $message 信息字符串
	 */
	public function write($message) {
		if ($this->ready) {
			$this->appender->append($message);
		}
	}
	
	/**
	 * 关闭
	 *
	 */
	public function close() {
		if ($this->ready) {
			$this->appender->close();
		}
	}
	
	/**
	 * 取得日志文件名格式
	 *
	 * @param string $filename 文件名
	 * @return string
	 */
	private function logFormat($filename) {
		$filename = preg_replace_callback("/%([a-zA-Z])/", array($this, "logFormatParseCallback"), $filename);
		return $filename;
	}
	
	private function logFormatParseCallback($match) {
		$dateFormats = array("Y", "m", "d", "H", "i", "s");
		if (in_array($match[1], $dateFormats)) {
			return date($match[1]);
		}
		return $match[0];
	}
	
	/**
	 * 析构方法
	 *
	 * 对象设为null时，关闭当前使用的writer
	 */
	public function __destruct() {
		$this->close();
	}
}

?>